import PageModel from "../../models/Page";
import CartModel from "../../models/Cart";
import Crypt from "../../utils/Crypt";
import CartTotal from "../../utils/CartTotal";
import UserModel from "../../models/User";

const pageModel = new PageModel()
const cartModel = new CartModel()
const userModel = new UserModel()

Page({
  data: {
    list: [],
    edit: false,
    areaList: false,
    supplier: false,
    totalQuantity: 0,
    totalPrice: 0,
    allSelected: false,
    areaText: '不同分区商品不能同时下单',
    supplierText: '不同供应商商品不能同时下单'
    // isLogin: false
  },
  onLoad: function (options) {
    // pageModel.getCart().then(response => {
    //
    // })
  },

  onShow() {
    // userModel.checkLogin(false).then(() => {
    userModel.checkLogin(true).then(() => {
      this.getCartData()
    })

  },

  getCartData() {
    cartModel.list().then(response => {
      let { data } = response
      data = Crypt.parse(data)

      data.forEach(x => {

        // selected
        x.selected = +x.selected !== 0
        const area = (x.product && x.product.area && x.product.area[0] && x.product.area[0].name && x.product.area[0].name.name) || ''
        x.areaName = area

        // sku
        if (x.selected_sku_text) {
          x.sku_desc = JSON.parse(x.selected_sku_text)
        }

        // 供应商
        // console.log(x)
        const supplier = (x.product && x.product.supplierName) || { id: 0, name: '' }
        x.supplier = supplier
      })

      this.setData({ list: data })

      // area list
      this.onArea()
      this.onSupplier()

      // total
      this.totalQuantity()
      this.totalPrice()
      this.allSelected()

      CartTotal.total(data)

    })
  },

  onGo() {
    wx.switchTab({
      url: '/pages/home/index'
      // url: '/pages/index/index'
    })
  },

  onEdit() {
    const result = !this.data.edit
    this.setData({ edit: result })
  },

  onArea() {
    const list = this.data.list.filter(x => x.selected).map(x => x.areaName)
    this.setData({ areaList: new Set([...list]).size > 1 })
  },

  onSupplier() {
    const list = this.data.list.filter(x => x.selected).map(x => x.supplier.id)
    this.setData({ supplierList: new Set([...list]).size > 1 })
  },

  onChecked(e) {
    const item = e.detail.item
    const result = !item.selected

    const list = this.data.list
    list.forEach(x => {
      if (x.id == item.id) {
        x.selected = result
      }
    })
    this.setData({ list })

    this.totalPrice()
    this.totalQuantity()
    this.allSelected()
    this.onArea()
    this.onSupplier()

    CartTotal.total(list)

    // delay
    cartModel.itemSelected({ ...item, selected: result }).then()
  },

  allSelected() {
    const result = this.data.list.every(x => x.selected)
    this.setData({ allSelected: result })
  },

  totalQuantity() {
    const selected = this.data.list.filter(x => x.selected)
    let total = 0
    selected.forEach(x => {
      total += +x.quantity
    })
    this.setData({ totalQuantity: total })
  },

  totalPrice() {
    const selected = this.data.list.filter(x => x.selected)
    let price = 0
    selected.forEach(x => {
      // price += +x.quantity * x.product.price
      price += +x.quantity * x.price
    })
    this.setData({ totalPrice: price })
  },

  changeAllSelected() {
    const result = this.data.allSelected
    const list = this.data.list
    list.forEach(x => {
      x.selected = !result
    })
    this.setData({
      list,
      allSelected: !result
    })

    cartModel.allSelected({ selected: !result }).then()

    this.totalPrice()
    this.totalQuantity()
    this.onArea()
    this.onSupplier()

    CartTotal.total(this.data.list)


  },

  deleteCart() {
    cartModel.remove().then(() => {
      const list = this.data.list.filter(x => x.selected === false)
      this.setData({ edit: false, list })
    })

    CartTotal.total(this.data.list)

  },

  clearCart() {
    cartModel.clear().then(() => {
      this.setData({ edit: false, list: [] })
    })

    CartTotal.total(this.data.list)

  },

  toOrder() {
    if (this.data.areaList) {
      return wx.showModal({ title: this.data.areaText, icon: 'error' })
    }

    if (this.data.supplierList) {
      return wx.showModal({ title: this.data.supplierText, icon: 'error' })
    }

    const params = {
      cart: true
    }

    wx.navigateTo({
      url: '/sub_main/pages/order/index?params=' + JSON.stringify(params)
    })
  },

  subItem(e) {
    const item = e.detail.item
    if (item.quantity > 1) {
      const list = this.data.list
      list.forEach(x => {
        if (x.id === item.id) {
          x.quantity--
          x.selected = true
        }
      })
      this.setData({ list })
      cartModel.decrement({ ...item }).then()
      this.totalQuantity()
      this.totalPrice()
      this.onArea()
      this.onSupplier()
      this.allSelected()

      CartTotal.total(this.data.list)

    }
  },

  addItem(e) {
    const item = e.detail.item
    if (item.quantity < item.product.stock) {
      const list = this.data.list
      list.forEach(x => {
        if (x.id === item.id) {
          x.quantity++
          x.selected = true
        }
      })
      this.setData({ list })
      cartModel.increment({ ...item }).then()
      this.totalQuantity()
      this.totalPrice()
      this.onArea()
      this.onSupplier()
      this.allSelected()

      CartTotal.total(this.data.list)

    } else {
      wx.showToast({ title: '库存不足', icon: 'error' })
    }
  },

  // 改变数量
  changeQuantity(e) {
    const item = e.detail.item
    const quantity = e.detail.quantity

    cartModel.changeQuantity({ id: item.id, quantity }).then(() => {
      const list = this.data.list
      list.forEach(x => {
        if (x.id === item.id) {
          x.quantity = quantity
          x.selected = true
        }
      })
      this.setData({ list })

      this.totalQuantity()
      this.totalPrice()
      this.onArea()
      this.onSupplier()
      this.allSelected()

      CartTotal.total(this.data.list)
    })
  }
});
